package cn.green.core.components.database.source;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wang.yishu
 * @version 1.0
 * @className QDataSource
 * @description QTable数据源
 * @date 2025/1/10 15:06
 */
public abstract class QDataSource extends AbstractRoutingDataSource {
    private Map<String, DataSource> dataSourceMap = new HashMap<>();

    public Map<String, DataSource> getDataSourceMap() {
        return dataSourceMap;
    }

    public void setDataSourceMap(Map<String, DataSource> dataSourceMap) {
        this.dataSourceMap = dataSourceMap;
    }

    public QDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
        for (Object key : targetDataSources.keySet()) {
            this.dataSourceMap.put(key.toString(), (DataSource) targetDataSources.get(key));
        }
    }

    public boolean isDataSourceAvailable(String key) {
        return isDataSourceAvailable(dataSourceMap.get(key));
    }

    private boolean isDataSourceAvailable(DataSource dataSource) {
        try (Connection ignored = dataSource.getConnection()) {
            return true;
        } catch (RuntimeException | SQLException e) {
            return false;
        }
    }

    public  void setDataSourceMap(String key , DataSource dataSource){
        if (!dataSourceMap.containsKey(key)) {
            dataSourceMap.put(key, dataSource);
            Map<Object, Object> targetData = new HashMap<>(dataSourceMap);
            super.setTargetDataSources(targetData);
            super.afterPropertiesSet();
        }
    }
    /**
     * 检查数据源是否已存在
     */
    public  boolean containsDataSource(String key) {
        return dataSourceMap.containsKey(key);
    }
}
